﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Cricket.LinqModel;
using Cricket.LinqData;

public partial class MatchReport : System.Web.UI.Page
{
    #region Variable Declaration
    IDataRepository _dataObject = new DataRepository();
    MatchSchedule matchSchedule;
    HttpCookie cookie;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        cookie = Request.Cookies["Admin"];
        if (!IsPostBack)
        {
            if (cookie == null)
                Response.Redirect("Login.aspx");
            else
                bindMatch();
        }
    }

    private void bindMatch()
    {
        matchSchedule = new MatchSchedule(_dataObject);
        List<GetMatchesForReportResult> lstResult = new List<GetMatchesForReportResult>();
        lstResult = matchSchedule.GetMatchesForReport();
        if (lstResult.Count > 0)
        {
            drpMatch.DataSource = lstResult;
            drpMatch.DataTextField = "Teams";
            drpMatch.DataValueField = "Id";
            drpMatch.DataBind();
            drpMatch.Items.Insert(0, new ListItem("Select Match", "0"));
        }
    }
    private static DataTable GetData(string query)
    {
        string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = query;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        return dt;
                    }
                }
            }
        }
    }
    protected void Show_Hide_OrdersGrid(object sender, EventArgs e)
    {
        ImageButton imgShowHide = (sender as ImageButton);
        GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
        if (imgShowHide.CommandArgument == "Show")
        {
            row.FindControl("pnlOrders").Visible = true;
            imgShowHide.CommandArgument = "Hide";
            imgShowHide.ImageUrl = "~/images/minus.png";
            string bookieId = grdBookie.DataKeys[row.RowIndex].Value.ToString();
            GridView grdCustomers = row.FindControl("grdCustomers") as GridView;

            matchSchedule = new MatchSchedule(_dataObject);
            List<GetMatchDetailsResult> lstResult = new List<GetMatchDetailsResult>();
            lstResult = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
            if (lstResult[0].MatchType.ToLower() == "one day" || lstResult[0].MatchType.ToLower() == "t20")
            {
                grdCustomers.Columns[5].Visible = false;
            }
            else
            {
                grdCustomers.Columns[5].Visible = true;
            }

            BindBookieCustomers(bookieId, grdCustomers);
        }
        else
        {
            row.FindControl("pnlOrders").Visible = false;
            imgShowHide.CommandArgument = "Show";
            imgShowHide.ImageUrl = "~/images/plus.png";
        }
    }
    private void BindBookieCustomers(string bookieId, GridView grdCustomers)
    {
        grdCustomers.ToolTip = bookieId;

        matchSchedule = new MatchSchedule(_dataObject);
        List<GetTeamNameByMatchDetailResult> lst1 = new List<GetTeamNameByMatchDetailResult>();
        lst1 = matchSchedule.GetTeamNameByMatchDetail(Convert.ToInt32(drpMatch.SelectedValue));
        if (lst1.Count > 0)
        {
            grdCustomers.Columns[3].HeaderText = lst1[0].Team1Name;
            grdCustomers.Columns[4].HeaderText = lst1[0].Team2Name;
            
        }
        else
        {
            grdCustomers.Columns[3].HeaderText = "Team 1";
            grdCustomers.Columns[4].HeaderText = "Team 2";
        }

        grdCustomers.DataSource = GetData(string.Format("SELECT DISTINCT C.Id AS CustomerId, C.Username AS CustomerName, SUM(BettingAmount) AS BettingAmount, SUM(TeamAAmount) AS TeamAAmount,SUM(TeamBAmount) AS TeamBAmount, SUM(TieAmount) AS TieAmount, SUM(DrawAmount) AS DrawAmount from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId WHERE C.AdminId = '{0}' AND (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = " + drpMatch.SelectedValue + "  AND B.BettingTypeId = 2 GROUP BY C.Username,C.Id ORDER BY C.Username asc", bookieId));
        grdCustomers.DataBind();
    }
    protected void OnOrdersGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView grdCustomers = (sender as GridView);
        grdCustomers.PageIndex = e.NewPageIndex;
        BindBookieCustomers(grdCustomers.ToolTip, grdCustomers);
    }
    protected void Show_Hide_ProductsGrid(object sender, EventArgs e)
    {
        ImageButton imgShowHide = (sender as ImageButton);
        GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
        if (imgShowHide.CommandArgument == "Show")
        {
            row.FindControl("pnlProducts").Visible = true;
            imgShowHide.CommandArgument = "Hide";
            imgShowHide.ImageUrl = "~/images/minus.png";
            int customerId = Convert.ToInt32((row.NamingContainer as GridView).DataKeys[row.RowIndex].Value);
            GridView grdAllCustomers = row.FindControl("grdAllCustomers") as GridView;
            
            matchSchedule = new MatchSchedule(_dataObject);
            List<GetMatchDetailsResult> lstResult = new List<GetMatchDetailsResult>();
            lstResult = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
            if (lstResult[0].MatchType.ToLower() == "one day" || lstResult[0].MatchType.ToLower() == "t20")
            {
                grdAllCustomers.Columns[6].Visible = false;
                grdAllCustomers.Columns[0].Visible = true;
            }
            else
            {
                grdAllCustomers.Columns[6].Visible = true;
                grdAllCustomers.Columns[0].Visible = false;

            }

            BindAllCustomers(customerId, grdAllCustomers);
        }
        else
        {
            row.FindControl("pnlProducts").Visible = false;
            imgShowHide.CommandArgument = "Show";
            imgShowHide.ImageUrl = "~/images/plus.png";
        }
    }
    private void BindAllCustomers(int customerId, GridView grdAllCustomers)
    {
        grdAllCustomers.ToolTip = customerId.ToString();
        matchSchedule = new MatchSchedule(_dataObject);
        List<GetTeamNameByMatchDetailResult> lst1 = new List<GetTeamNameByMatchDetailResult>();
        lst1 = matchSchedule.GetTeamNameByMatchDetail(Convert.ToInt32(drpMatch.SelectedValue));
        if (lst1.Count > 0)
        {
            grdAllCustomers.Columns[4].HeaderText = lst1[0].Team1Name;
            grdAllCustomers.Columns[5].HeaderText = lst1[0].Team2Name;
            //grdAllCustomers.Columns[4].HeaderText = "Team 1";
            //grdAllCustomers.Columns[5].HeaderText = "Team 2";
        }
        else
        {
            grdAllCustomers.Columns[4].HeaderText = "Team 1";
            grdAllCustomers.Columns[5].HeaderText = "Team 2";
        }
        grdAllCustomers.DataSource = GetData(string.Format("SELECT CASE WHEN B.IsDraw = 1 THEN CASE CB.BetFor WHEN 'L' THEN B.DrawLagadi ELSE B.DrawKhadhi END WHEN B.IsTie = 1 THEN CASE CB.BetFor WHEN 'L' THEN B.TieLagadi ELSE B.TieKhadhi END ELSE CASE CB.BetFor WHEN 'L' THEN B.LagadiRate ELSE B.KhadhiRate END END AS Rate,CB.BetFor AS BettingFor,BettingAmount AS BettingAmount, TeamAAmount AS TeamAAmount,TeamBAmount AS TeamBAmount, TieAmount AS TieAmount, DrawAmount AS DrawAmount, CONVERT(varchar(20),DATEADD(MI,30,DATEADD(hh,5,CB.CreatedDate)),113) As Date,T.[Abbrivation] AS TeamName from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN Team T ON B.TeamId = T.Id WHERE C.Id = '{0}' AND (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = " + drpMatch.SelectedValue + "  AND B.BettingTypeId = 2 ", customerId));
        
        grdAllCustomers.DataBind();
    }
    protected void OnProductsGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView grdAllCustomers = (sender as GridView);
        grdAllCustomers.PageIndex = e.NewPageIndex;
        BindAllCustomers(int.Parse(grdAllCustomers.ToolTip), grdAllCustomers);
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["Admin"];
        if (cookie == null)
        {
            Response.Redirect("Login.aspx");
        }
        else
        {
            DataTable dt = new DataTable();
            Admin admin = new Admin(_dataObject);
            List<AdminResult> adminResult = new List<AdminResult>();
            adminResult = admin.GetAdminDetailsById(Convert.ToInt32(cookie["AdminId"]));
            if (adminResult[0].CommonRate == 2)
            {
                //dt = GetData("select A.Id AS BookieId, A.FirstName + ' ' + A.LastName AS BookieName, SUM((CB.BettingAmount) * -1) AS BettingAmount, SUM((TeamAAmount) * -1) AS TeamAAmount,SUM((TeamBAmount) * -1) AS TeamBAmount, SUM((TieAmount) * -1) AS TieAmount, (SUM(DrawAmount) * -1) AS DrawAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 2 AND A.Id IN (Select Cl.AdminId From Client Cl) GROUP BY A.Id, A.FirstName, A.LastName");
                dt = GetData("select A.Id AS BookieId, A.FirstName + ' ' + A.LastName AS BookieName, SUM((CB.BettingAmount) * -1) AS BettingAmount, SUM((TeamAAmount) * -1) AS TeamAAmount,SUM((TeamBAmount) * -1) AS TeamBAmount, SUM((TieAmount) * -1) AS TieAmount, (SUM(DrawAmount) * -1) AS DrawAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 2 GROUP BY A.Id, A.FirstName, A.LastName");
            }
            else
            {
                dt = GetData("select A.Id AS BookieId, A.FirstName + ' ' + A.LastName AS BookieName, SUM((CB.BettingAmount) * -1) AS BettingAmount, SUM((TeamAAmount) * -1) AS TeamAAmount,SUM((TeamBAmount) * -1) AS TeamBAmount, SUM((TieAmount) * -1) AS TieAmount, (SUM(DrawAmount) * -1) AS DrawAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE (B.AdminId = " + Convert.ToInt32(cookie["AdminId"]) + " OR B.AdminId = 3) AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 2 GROUP BY A.Id, A.FirstName, A.LastName");
                //dt = GetData("select A.Id AS BookieId, A.FirstName + ' ' + A.LastName AS BookieName, SUM((CB.BettingAmount) * -1) AS BettingAmount, SUM((TeamAAmount) * -1) AS TeamAAmount,SUM((TeamBAmount) * -1) AS TeamBAmount, SUM((TieAmount) * -1) AS TieAmount, (SUM(DrawAmount) * -1) AS DrawAmount from Client C INNER JOIN Admin A ON C.AdminId = A.Id INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON CB.BettingId = B.Id WHERE B.AdminId = 3 AND CB.MatchSchduleId = " + drpMatch.SelectedValue + " AND B.BettingTypeId = 2 GROUP BY A.Id, A.FirstName, A.LastName");
            }
            matchSchedule = new MatchSchedule(_dataObject);
            List<GetTeamNameByMatchDetailResult> lst1 = new List<GetTeamNameByMatchDetailResult>();
            lst1 = matchSchedule.GetTeamNameByMatchDetail(Convert.ToInt32(drpMatch.SelectedValue));
            if (lst1.Count > 0)
            {
                grdBookie.Columns[3].HeaderText = lst1[0].Team1Name;
                grdBookie.Columns[4].HeaderText = lst1[0].Team2Name;
                //grdBookie.Columns[3].HeaderText = "Team 1";
                //grdBookie.Columns[4].HeaderText = "Team 2";
            }
            else
            {
                grdBookie.Columns[3].HeaderText = "Team 1";
                grdBookie.Columns[4].HeaderText = "Team 2";
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                layerError.Attributes.Add("style", "display:none;");
                layerError.InnerHtml = "";
                grdBookie.DataSource = dt;
                grdBookie.DataBind();
            }
            else
            {
                grdBookie.DataSource = null;
                grdBookie.DataBind();
                layerError.Attributes.Add("style", "display:block;");
                layerError.InnerHtml = "No results declared yet!";
            }
        }
    }
    protected void grdBookie_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        matchSchedule = new MatchSchedule(_dataObject);
        List<GetMatchDetailsResult> lstResult = new List<GetMatchDetailsResult>();
        lstResult = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
        if (lstResult[0].MatchType.ToLower() == "one day" || lstResult[0].MatchType.ToLower() == "t20")
        {
            grdBookie.Columns[5].Visible = false;
        }
        else
        {
            grdBookie.Columns[5].Visible = true;
        }
    }
    
}